import {CheckOutlined, InboxOutlined, UndoOutlined} from '@ant-design/icons';
import {
  Layout,
  message,
  Form,
  DatePicker,
  Upload,
  Space,
  UploadProps,
  Row,
  Col,
  Input,
  Modal,
  Select,
  Progress,
  Button,
} from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined, DeleteOutlined, EditOutlined, UploadOutlined } from '@ant-design/icons';

import '@/assets/css/index.less';
import ProForm, { ProFormText, ProFormSelect } from '@ant-design/pro-form';
import { useForm } from 'antd/es/form/Form';
import { getPhotoCategoryList, releasePhoto, uploadList } from '@/services/pictureManager';
import VideoUpload from '@/components/videoUpload';
import { useLocation } from 'umi';
import { getOneById, updateVideo } from '@/services/videoManager';
import MultiImgUpload from '@/components/multiImgUpload';

const { Dragger } = Upload;
const { TextArea } = Input;
const { Header } = Layout;
import {BASE_URL} from "../../../../proxyConfig";

const MNTPrefix = BASE_URL;

const VideoPublish: React.FC = () => {
  const playerRef = React.useRef(null);
  const [videoInfo, setVideoInfo] = useState({});
  const [coverResponseInfo, setCoverResponseInfo] = useState([]);
  const location = useLocation();
  const [coverImageFile, setCoverImageFile] = useState<UploadFile[]>([]);
  const [videoResponse, setVideoResponse] = useState({});
  const [currentFormValues, setCurrentFormValues] = useState(location.state?.videoForm);
  const getOneVideoByID = async () => {
    const res = await getOneById({ id: currentFormValues.id });
    setVideoResponse(res.data);
    coverImageFile.push(JSON.parse(JSON.stringify(res.data).replace('coverImage', 'url')));
  };
  useEffect(() => {
    getOneVideoByID();
  }, []);
  let onSubmit;
  try {
    onSubmit = async (values) => {
      const hide = message.loading('正在上传视频，可能时间会比较长，请您耐心等待。');

      if (
        Object.keys(videoInfo).length == 0 &&
        values.fileList &&
        values.fileList.fileList.length === 0
      ) {
        message.error('视频为空，请上传视频！');
        return;
      }
      let tmp = {};
      //modify cover image
      if (coverImageFile[0].response) {
        tmp = {
          ...values,
          id: currentFormValues.id,

          coverImage: coverImageFile[0].response.data.data[0].src,
        };
      } else {
        //not modify cover image
        tmp = {
          ...values,
          id: currentFormValues.id,
        };
      }
      tmp['url'] = videoResponse.url || videoResponse.localurl;
      const res = await updateVideo(tmp);
      if (res.code == 0) {
        message.success('上传成功');
        hide();
        setVideoInfo({});
        window.location.href = window.location.href.replace(/videoEdit/, 'mediaManagement');
      } else {
        message.info(res.data);
        hide();
      }
    };
  } catch (error) {
    console.log(error);
  }

  const [form] = useForm();
  const [form_coverImage] = useForm();
  const formLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 14,
    },
  };

  const goBack = () => {
    window.history.back();
  };

  const validateVideo = (rule, value, callback) => {
    if (Object.keys(videoResponse).length != 0) {
      callback();
    } else if (!value) {
      callback('请上传视频！');
    }
  };
  return (
    <PageContainer
      header={{
        title: '视频编辑',
        breadcrumb: {
          items: [
            {
              // path: '',
              title: '视频管理',
            },
            {
              title: '视频编辑',
            },
          ],
        },
      }}
    >
      <ProForm
        form={form}
        // formRef={videoForm}
        layout="horizontal"
        {...formLayout}
        initialValues={currentFormValues || {}}
        onFinish={onSubmit}
        onReset={goBack}
        submitter={{
          render: (_, dom) => (
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Space>
                {/*{dom}*/}
                {<Button onClick={() => {
                  _.reset()
                }}><UndoOutlined />返回</Button>}
                {<Button type={"primary"} onClick={() => {
                  _.submit()
                }}><CheckOutlined />提交</Button>}

              </Space>
            </div>
          ),
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '主题名称必填',
            },
          ]}
          width="md"
          name="title"
          placeholder="请填写主题名称"
          label="主题"
        />
        <Form.Item label="描述" name="description">
          <TextArea
            className=""
            showCount
            maxLength={300}
            // style={{ height: 120, marginBottom: 24, width: 300}}
            // onChange={onChange}
            placeholder="输入备注信息"
          />
        </Form.Item>

        <Form.Item label="封面图片" name="coverImage">
          <MultiImgUpload
            target="cover"
            form={form_coverImage}
            fileList={coverImageFile}
            setFileList={setCoverImageFile}
            url={'/api/v1/photo/uploadList'}
            fileResponse={coverResponseInfo}
            setResponse={setCoverResponseInfo}
          />
        </Form.Item>

        <Form.Item
          label="上传视频"
          name="fileList"
          rules={[
            {
              required: true,
              message: '请上传视频',
              validator: validateVideo,
            },
          ]}
          // style={{
          //     display: !displayVideo?'block':'none'
          // }}
        >
          <VideoUpload
            // fileList={fileList}
            // setFileList={setFileList}
            // url={"/api/v1/photo/uploadList"}
            fileResponse={videoResponse}
            setResponse={setVideoResponse}
          />
        </Form.Item>
      </ProForm>
    </PageContainer>
  );
};
export default VideoPublish;
